package com.sogo;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.app.AlertDialog;
import android.os.Bundle;
import android.provider.MediaStore;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.sogo.FriendsListMainScreen;

public class SettingMenu extends Activity {
	private String email;
	private String password;
	private String username;
	private String firstname;
	private String lastname;
	private String updatetime;
	private String hidden;
	private EditText etoldpassword;
	private EditText etnewpassword1;
	private EditText etnewpassword2;
	private Uri mImageCaptureUri;
	//private ImageView mImageView;
	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int PICK_FROM_FILE = 3;
	InputStream is;
	private static final String DATABASE_TABLE = "UserInfo";
	DBAdapter db = new DBAdapter(this);
	ServerConnection serverConn = new ServerConnection();
	FriendsListMainScreen main = new FriendsListMainScreen();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settingmenu);
		Button uploadAvatar = (Button) findViewById(R.id.uploadAvatar);
		checkbox = (CheckBox) findViewById(R.id.enablelocationcheckBox);
		db.open();
		int locationFlag = Integer.parseInt(db.getEnableLocation());
		db.close();

		String avpath = db.avatarPath();
		Bitmap bitmap = null;
		loadUserAvatar(); //load the user avatar when user enters settings. Image is loaded from remote server

		if (locationFlag == 0) { //checks to see if the user is enabling updates. 
			checkbox.setChecked(false);
		} else {
			checkbox.setChecked(true);
		}
		//start the pick image from Gallery or Camera.
		final String[] items = new String[] { "Take from camera", "Select from Gallery" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, items);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("Select Image");
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) { // pick from
																	// camera
				if (item == 0) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

					mImageCaptureUri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), "tmp_avatar_"
							+ String.valueOf(System.currentTimeMillis())
							+ ".jpg"));

					intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
							mImageCaptureUri);

					try {
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (ActivityNotFoundException e) {
						e.printStackTrace();
					}
				} else { // pick from file
					Intent intent = new Intent();

					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);

					startActivityForResult(Intent.createChooser(intent,
							"Complete action using"), PICK_FROM_FILE);
				}
			}
		});
		//end picture selection.
		final AlertDialog dialog = builder.create();

		uploadAvatar.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				dialog.show(); //when button is pushed prompt user dialog for gallery or sd selection
			}
		});
		checkbox.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Perform action on clicks, depending on whether it's now
				// checked
				db.open();
				Cursor c = db.getUser();
				if (c.moveToFirst()) {
					username = c.getString(1);
					firstname = c.getString(2);
					lastname = c.getString(3);
					email = c.getString(4);
					password = c.getString(5);
				}
				String userID = db.getOwnID();
				db.close();
				if (((CheckBox) v).isChecked()) {
					hidden = "N";
					db.updateEnableLocation(Integer.parseInt(userID), 1);
					sendHidden(username, hidden);
				} else {
					hidden = "Y";
					db.updateEnableLocation(Integer.parseInt(userID), 0);
					sendHidden(username, hidden);
				}
			}
		});
		Spinner spinner = (Spinner) findViewById(R.id.spinner);
		ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
				this, R.array.refresh_times,
				android.R.layout.simple_spinner_item);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter1);
		spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
		int currentInterval = Integer.parseInt(db.getRefreshRate());
		int spinnerIndex = 0;
		if (currentInterval == 3600000) {
			spinner.setSelection(0);
		} else if (currentInterval == 1800000) {
			spinner.setSelection(1);
		} else if (currentInterval == 900000)
			spinner.setSelection(2);
		else if (currentInterval == 300000)
			spinner.setSelection(3);
		else if (currentInterval == 60000)
			spinner.setSelection(4);
		else if (currentInterval == 30000)
			spinner.setSelection(5);

		Button showPopUpButton = (Button) findViewById(R.id.buttonShowPopUp);
		showPopUpButton.setOnClickListener(new OnClickListener() {

			// @Override
			public void onClick(View v) {
				updateEmail();
			}
		});

		Button showPopUpButton2 = (Button) findViewById(R.id.changePassword);
		showPopUpButton2.setOnClickListener(new OnClickListener() {

			// @Override
			public void onClick(View v) {
				updatePassword();
			}
		});
	}

	private void loadUserAvatar()
	{
		int code=0;
		String userid = db.getOwnID();
		String url = "http://suopensim.com/app/images/" + userid+ ".jpg";
		String urlNoAvatar="http://suopensim.com/app/images/noavatar.png";
		/*
		Bitmap bitmap1 = BitmapFactory
				.decodeStream((InputStream) new URL(url).getContent());
		mImageView.setImageBitmap(bitmap1);*/
		
		 try {
		        HttpURLConnection.setFollowRedirects(false);
		        int Count = 1;
		        URL testURL;
		            testURL = new URL((url));
		            HttpURLConnection con = (HttpURLConnection) testURL.openConnection();
		            con.setRequestMethod("HEAD");
		            Log.e("RESPONCE", Integer.toString(con.getResponseCode()));
		            code=con.getResponseCode();
		    } catch (Exception e) {

		    }

		LoaderImageView image = (LoaderImageView) findViewById(R.id.loaderImageView);
		
		if(code!=404)
			image.setImageDrawable(url);
		else if(code==404)
			image.setImageDrawable(urlNoAvatar);
	
	}


	private void updateEmail() {

		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle("Change Email");
		helpBuilder.setMessage("Enter a new Email");
		db.open();
		Cursor c = db.getUser();
		if (c.moveToFirst()) {
			username = c.getString(1);
			firstname = c.getString(2);
			lastname = c.getString(3);
			email = c.getString(4);
			password = c.getString(5);
		}
		db.close();
		final EditText input = new EditText(this);
		input.setSingleLine();
		input.setText(email);
		helpBuilder.setView(input);
		helpBuilder.setPositiveButton("Submit",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						email = input.getText().toString();
						int rID = Integer.parseInt(db.getOwnID());
						Context context = getApplicationContext();
						Toast.makeText(context, email, Toast.LENGTH_LONG)
								.show();

						db.open();
						Cursor c = db.getUser();
						c.moveToLast();
						db.updateUser(rID, username, firstname, lastname,
								email, password);
						Cursor cs = db.getUser();
						if (cs.moveToFirst()) {
							do {
								DisplayUser(cs);
							} while (cs.moveToNext());
						}
						db.close();

						final int TIMEOUT_MILLISEC = 30000;
						JSONArray jsonArray = null;
						try {
							JSONObject json = new JSONObject();
							json.put("Username", username);
							json.put("Email", email);
							HttpParams httpParams = new BasicHttpParams();
							HttpConnectionParams.setConnectionTimeout(
									httpParams, TIMEOUT_MILLISEC);
							HttpConnectionParams.setSoTimeout(httpParams,
									TIMEOUT_MILLISEC);
							HttpClient client = new DefaultHttpClient(
									httpParams);
							String url = "http://www.suopensim.com/app/updateEmail.php";

							HttpPost request = new HttpPost(url);
							request.setEntity(new ByteArrayEntity(json
									.toString().getBytes("UTF8")));
							request.setHeader("json", json.toString());
							HttpResponse response = client.execute(request);
							HttpEntity entity = response.getEntity();
							// If the response does not enclose an entity, there
							// is no need
							if (entity != null) {
								InputStream instream = entity.getContent();
								String result = convertStreamToString(instream);
								try {
									jsonArray = new JSONArray(result);
									// return jsonArray;
								} catch (Throwable t) {
									jsonArray = null;
									// jsonArray;
								}

							}
						} catch (Throwable t) {
							Log.e(LoginRegistrationScreen.class.getName(),
									"Request failed: " + t.toString());
						}

					}

				});

		helpBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// Do nothing but close the dialog
					}
				});

		// Remember, create doesn't show the dialog
		AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();
	}

	private void updatePassword() {

		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle("Change Password");
		helpBuilder.setMessage("Enter a new Password");

		LayoutInflater inflater = LayoutInflater.from(this);
		final View checkboxLayout = inflater.inflate(R.layout.editpassword,
				null);
		helpBuilder.setView(checkboxLayout);

		helpBuilder.setPositiveButton("Submit",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						etoldpassword = (EditText) checkboxLayout
								.findViewById(R.id.oldpassword);
						etnewpassword1 = (EditText) checkboxLayout
								.findViewById(R.id.newpassword1);
						etnewpassword2 = (EditText) checkboxLayout
								.findViewById(R.id.newpassword2);
						String oldpassword = etoldpassword.getText().toString();
						String newpassword1 = etnewpassword1.getText()
								.toString();
						String newpassword2 = etnewpassword2.getText()
								.toString();
						String encriptedPass;

						Context context2 = getApplicationContext();
						Toast.makeText(context2, newpassword1,
								Toast.LENGTH_LONG).show();
						db.open();
						Cursor c = db.getUser();
						if (c.moveToFirst()) {
							username = c.getString(1);
							firstname = c.getString(2);
							lastname = c.getString(3);
							email = c.getString(4);
							password = c.getString(5);
						}
						db.close();

						if (password.equals(serverConn
								.encryptPassword(oldpassword))) {
							Toast.makeText(context2, oldpassword,
									Toast.LENGTH_LONG).show();
							if (newpassword1.equals(newpassword2)) {

								long rID = 1;

								db.open();
								Cursor cc = db.getUser();
								cc.moveToLast();
								db.updateUser(rID, username, firstname,
										lastname, email, serverConn
												.encryptPassword(etnewpassword2
														.getText().toString()));
								Cursor cs = db.getUser();
								if (cs.moveToFirst()) {
									do {
										DisplayUser(cs);
									} while (cs.moveToNext());
								}
								db.close();
								encriptedPass = serverConn
										.encryptPassword(newpassword1);
								final int TIMEOUT_MILLISEC = 30000;
								JSONArray jsonArray = null;
								try {
									JSONObject json = new JSONObject();
									json.put("Username", username);
									json.put("Password", encriptedPass);
									HttpParams httpParams = new BasicHttpParams();
									HttpConnectionParams.setConnectionTimeout(
											httpParams, TIMEOUT_MILLISEC);
									HttpConnectionParams.setSoTimeout(
											httpParams, TIMEOUT_MILLISEC);
									HttpClient client = new DefaultHttpClient(
											httpParams);
									String url = "http://www.suopensim.com/app/updatePassword.php";

									HttpPost request = new HttpPost(url);
									request.setEntity(new ByteArrayEntity(json
											.toString().getBytes("UTF8")));
									request.setHeader("json", json.toString());
									HttpResponse response = client
											.execute(request);
									HttpEntity entity = response.getEntity();
									// If the response does not enclose an
									// entity, there is no need
									if (entity != null) {
										InputStream instream = entity
												.getContent();
										String result = convertStreamToString(instream);
										try {
											jsonArray = new JSONArray(result);
											// return jsonArray;
										} catch (Throwable t) {
											jsonArray = null;
											// jsonArray;
										}

									}
								} catch (Throwable t) {
									Log.e(LoginRegistrationScreen.class
											.getName(),
											"Password Update Failed: "
													+ t.toString());
								}
							} else {
								Context context = getApplicationContext();
								Toast.makeText(context,
										"The new passwords to not match",
										Toast.LENGTH_LONG).show();
							}
						} else {
							Context context = getApplicationContext();
							Toast.makeText(
									context,
									"The old password does not match your actual password",
									Toast.LENGTH_LONG).show();
						}
					}
				});

		helpBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}
				});

		// Remember, create doesn't show the dialog
		AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exit:
			db.open();
			db.deleteDB();
			Intent k = new Intent();
			k.setClassName("com.sogo", "com.sogo.LoginRegistrationScreen");
			startActivity(k);
			finish();
			return true;
		case R.id.setting:
			Intent i = new Intent();
			i.setClassName("com.sogo", "com.sogo.SettingMenu");
			startActivity(i);
			return true;
		case R.id.addfriend:
			Intent s = new Intent();
			s.setClassName("com.sogo", "com.sogo.SearchFriend");
			startActivity(s);
			return true;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case PICK_FROM_CAMERA:
			doCrop();
			break;

		case PICK_FROM_FILE:
			mImageCaptureUri = data.getData();

			doCrop();

			break;
		case CROP_FROM_CAMERA: //after croping
			Bundle extras = data.getExtras();
			if (extras != null) {
                String userid=db.getOwnID();
				Bitmap photo = extras.getParcelable("data");
				//start upload code
				ByteArrayOutputStream bao = new ByteArrayOutputStream();
				photo.compress(Bitmap.CompressFormat.JPEG, 100, bao);
				byte[] ba = bao.toByteArray();
                String ba1 = Base64.encodeBytes(ba);
                ArrayList<NameValuePair> nameValuePairs = new
                ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("image", ba1));
                String url="http://suopensim.com/app/uploadAvatar.php?uid="+userid;
                try {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new
                        HttpPost(url);
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();
                } catch (Exception e) {

                        Log.e("log_tag", "Error in http connection " + e.toString());

                }
                //end upload code
                loadUserAvatar();//reload the image after uploading the new one.
			}
			File f = new File(mImageCaptureUri.getPath());
			if (f.exists())
				f.delete();
			break;
		}
	}

	private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(
				intent, 0);

		int size = list.size();

		if (size == 0) {
			Toast.makeText(this, "Can not find image crop app",
					Toast.LENGTH_SHORT).show();

			return;
		} else {
			intent.setData(mImageCaptureUri);

			intent.putExtra("outputX", 200);
			intent.putExtra("outputY", 200);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i, CROP_FROM_CAMERA);
			} else {
				for (ResolveInfo res : list) {
					final CropOption co = new CropOption();

					co.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					co.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					co.appIntent = new Intent(intent);

					co.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(co);
				}

				CropOptionAdapter adapter = new CropOptionAdapter(
						getApplicationContext(), cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Choose Crop App");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										CROP_FROM_CAMERA);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					public void onCancel(DialogInterface dialog) {

						if (mImageCaptureUri != null) {
							getContentResolver().delete(mImageCaptureUri, null,
									null);
							mImageCaptureUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}
		}
	}

	public void DisplayUser(Cursor c) {
		Toast.makeText(
				this,
				"id: " + c.getString(0) + "\n" + "UserName: " + c.getString(1)
						+ "\n" + "First Name: " + c.getString(2) + "\n"
						+ "Last Name: " + c.getString(3) + "\n" + "Email: "
						+ c.getString(4) + "\n" + "Password: " + c.getString(5),
				Toast.LENGTH_LONG).show();
	}

	public class MyOnItemSelectedListener implements OnItemSelectedListener {
		/*
		 * Right now, when the settings activity starts, it auto inserts the
		 * selected item. Should be set to what it already is.
		 * 
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.widget.AdapterView.OnItemSelectedListener#onItemSelected(
		 * android.widget.AdapterView, android.view.View, int, long)
		 */

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			parent.getContext();

			int frequency = 0;
			String userID = db.getOwnID();
			Context context = getApplicationContext();
			CharSequence text = "Hello toast message: ";
			int duration = Toast.LENGTH_LONG;
			if (pos == 0) {// 60 mintues
				frequency = 3600000;
				db.updateRefreshRate(Integer.parseInt(userID), frequency);
				text = text + "updated her to 60!";

			} else if (pos == 1) {// 30 minutes
				// FriendsListMainScreen.refreshRate = 1800000;
				frequency = 1800000;
				db.updateRefreshRate(Integer.parseInt(userID), frequency);
				text = text + "updated her to 30 minutes";
			} else if (pos == 2) {// 10 minutes
				// FriendsListMainScreen.refreshRate = 900000;
				frequency = 900000;
				db.updateRefreshRate(Integer.parseInt(userID), frequency);
				text = text + "updated her to 10!";
			} else if (pos == 3) {// 5 minutes
				// / FriendsListMainScreen.refreshRate = 300000;
				frequency = 300000;
				db.updateRefreshRate(Integer.parseInt(userID), frequency);
				text = text + "updated to 5 minutes";
			}

			else if (pos == 4) {
				// FriendsListMainScreen.refreshRate = 60000;
				frequency = 60000;
				db.updateRefreshRate(Integer.parseInt(userID), frequency);
				text = text + "updated to 1 minute";
			}

			else { // update to 30 seconds, who in their right mind would do
					// that.
					// FriendsListMainScreen.refreshRate = (30000);
				frequency = 30000;
				db.updateRefreshRate(Integer.parseInt(userID), frequency);
				text = text + "updated to 30s, your crazy.";
			}
			Toast toast = Toast.makeText(context, text, duration);
			// toast.show();
			FriendsListMainScreen.lm
					.removeUpdates(FriendsListMainScreen.locationListener);
			// oldRate = refreshRate;
			FriendsListMainScreen.lm.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, frequency, 5,
					FriendsListMainScreen.locationListener);
			FriendsListMainScreen.lm.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, frequency, 5,
					FriendsListMainScreen.locationListener);
		}

		public void onNothingSelected(AdapterView parent) {
			// Do nothing.
		}

	}

	public void sendTime(int time) {
		final int TIMEOUT_MILLISEC = 30000;
		JSONArray jsonArray = null;
		try {
			JSONObject json = new JSONObject();
			json.put("Username", username);
			json.put("Time", time);
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			String url = "http://www.suopensim.com/app/updateTime.php";

			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes(
					"UTF8")));
			request.setHeader("json", json.toString());
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);
				try {
					jsonArray = new JSONArray(result);
					// return jsonArray;
				} catch (Throwable t) {
					jsonArray = null;
					// jsonArray;
				}

			}
		} catch (Throwable t) {
			Log.e(LoginRegistrationScreen.class.getName(), "Request failed: "
					+ t.toString());
		}
	}

	public void sendHidden(String user, String hide) {
		final int TIMEOUT_MILLISEC = 30000;
		JSONArray jsonArray = null;
		try {
			JSONObject json = new JSONObject();
			json.put("Username", user);
			json.put("Hidden", hide);
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			String url = "http://www.suopensim.com/app/updateHidden.php";

			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes(
					"UTF8")));
			request.setHeader("json", json.toString());
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);
				try {
					jsonArray = new JSONArray(result);
					// return jsonArray;
				} catch (Throwable t) {
					jsonArray = null;
					// jsonArray;
				}

			}
		} catch (Throwable t) {
			Log.e(LoginRegistrationScreen.class.getName(), "Request failed: "
					+ t.toString());
		}
	}

	public static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	private CheckBox checkbox;

}